<template>
  <div class="swiper-container">
    <div class="swiper-wrapper">
      <div v-for="(item, index) in list" :key="index" class="swiper-slide">
        <img :src="item.imageUrl" :alt="item.typeTitle+index" class="swiper-lazy" />
      </div>
    </div>
    <div class="swiper-button-next"></div>
    <div class="swiper-button-prev"></div>
    <div class="swiper-pagination"></div>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, watchEffect, nextTick, onMounted } from "vue";
import Swiper,{Navigation, Pagination } from "swiper";
import "swiper/swiper-bundle.css";

// 验证组件传值类型
interface Data {
  list: object[];
  loop?: boolean;
  autoplay?: boolean;
  delay?: number;
  speed?: number;
  spaceBetween?: number;
}

interface Model {
  bannerList: object[];
}

const swiperBox = {
  name: "swiperBox",
  components: {
    Swiper,
  },
  props: {
    // 轮播数据
    list: {
      type: Array,
      default: () => [],
    },
    // 是否连续轮播
    loop: {
      type: Boolean,
      default: true,
    },
    // 是否自动轮播
    autoplay: {
      type: Boolean,
      default: true,
    },
    // 自动轮播的时间
    delay: {
      type: Number,
      default: 3000,
    },
    // 轮播的速度
    speed:{
      type:Number,
      default: 2000
    },
    // 轮播之间的间距
    spaceBetween: {
      type: Number,
      default: 80
    } 
  },
  setup(props: Data) {
    const data: Model = reactive({
      bannerList: [],
    });

    watchEffect(() => {
      data.bannerList = props.list;
      let autoplay: boolean | object;
      if (props.autoplay) {
        autoplay = {
          delay: props.delay
        };
      } else autoplay = false;
      
      nextTick(() => {
        new Swiper(".swiper-container", {
          loop: props.loop,
          autoplay:{
            delay:1000
          },
          spaceBetween:props.spaceBetween,
          speed:props.speed,
          navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
          },
          pagination: {
            el: ".swiper-pagination",
          },
        });
      });
    });

    onMounted(() => {
      Swiper.use([Navigation, Pagination]);
    });

    return {
      ...toRefs(data),
    };
  },
};

export default swiperBox;
</script>

<style lang="scss" scoped>
.swiper-pagination {
  bottom: 20px;
}
.swiper-slide {
  width: 100%;
  margin: 15px 0;
  img {
    width: 100%;
    height: auto;
  }
}
</style>